package @actionPackage@.util;

import java.util.List;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.framework.EntityQuery;

@Scope(ScopeType.PAGE)
public abstract class GenericEntityQuery<E> extends EntityQuery<E> {

	private static final long serialVersionUID = 1L;

	private Integer page = 1;

	public List<E> getResultListWithPaging() {
		Integer entityCount = entityCount();

		setFirstResult((page > 0 ? page - 1 : 0) * getMaxResults());

		PagedList<E> entityList = new PagedList<E>(this.getResultList(),
				entityCount, getMaxResults());

		return entityList;
	}

	private List<E> countList = null;

	public Integer entityCount() {
		if (countList == null) {
			countList = this.getEntityManager().createQuery(getEjbql())
					.getResultList();
		}
		return countList.size();
	}

	@Override
	public void refresh() {
		if (getMaxResults() != null) {
			countList = null;
			Integer entityCount = entityCount();

			if (page > (entityCount / getMaxResults()) && (entityCount % getMaxResults()) == 0) {
				page = entityCount / getMaxResults();
			}
			super.refresh();
		}
	}

	public void orderParameter(String orderColumn, String orderDirection) {
		super.setOrderColumn(orderColumn);
		super.setOrderDirection(orderDirection);
	}

	public void setPage(Integer page) {
		this.page = page;
	}

	public Integer getPage() {
		return page;
	}

}
